package com.cn.jdia.tas.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBManager4SqlServer {

	public static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
	public static final String URL = "jdbc:sqlserver://172.20.1.12:1433; DatabaseName=v3x";
	public static final String USER = "Sa";
	public static final String PASS = "Qd83789951";

	private static DBManager4SqlServer per = null;

	private Connection conn = null;
	private Statement stmt = null;

	private PreparedStatement ps = null;

	public DBManager4SqlServer() {

	}

	public static DBManager4SqlServer createInstance() {
		if (per == null) {
			per = new DBManager4SqlServer();
			per.initDB();
		}
		return per;
	}

	public void initDB() {
		try {
			Class.forName(DRIVER);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void connectDB() {
		System.out.println("Connecting to database...");
		try {
			Connection conn = DriverManager.getConnection(URL, USER, PASS);
			stmt = conn.createStatement();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("connect sqlserver success!");
	}

	public PreparedStatement connectDB2(String sql) {
		try {
			Connection conn = DriverManager.getConnection(URL, USER, PASS);
			ps = conn.prepareStatement(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ps;
	}

	public void closeDB() {
		System.out.println("Close connection to database..");
		try {
			if (stmt != null) {
				stmt.close();
			}

			if (ps != null) {
				ps.close();
			}
			
			if (conn != null) {
				conn.close();
			} else {
				System.out.println("conn is null---");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("Close connection successful");
	}

	public ResultSet executeQuery(String sql) {
		ResultSet rs = null;
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	public int executeUpdate(String sql) {
		int ret = 0;
		try {
			ret = stmt.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ret;
	}

	public Connection getConn() {
		return conn;
	}

}
